<template>
  <el-dialog title="发放优惠券" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="30%">

    <el-form ref="dataForm" style="margin-left:50px;">
      <el-form-item>
        <el-select
          v-model="coupongid"
          filterable
          remote
          :remote-method="remoteMethod"
          placeholder="请选择优惠券"
          :loading="loading"
        >
          <i slot="prefix" class="iconfont iconquanchangyouhui" style="font-size:16px;color:#666;padding:0 3px;" />
          <el-option
            v-for="item in couponOptions"
            :key="item.gid"
            :label="item.name"
            :value="item.gid"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <span v-if="userIds===''"><i class="iconfont icongerenyouhuiquan" style="font-size:18px;color:#666;padding:0 5px;" />全员发送</span>
        <span v-else><i class="iconfont icongerenyouhuiquan" style="font-size:18px;color:#666;padding:0 5px;line-heigth:inherit" />特定用户</span>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="provideCoupon">
        发送
      </el-button>
    </div>
  </el-dialog>
</template>

<script>

import { getCoupon, grant } from '@/api/coupon'

export default {

  props: {
    coupon: {
      type: Object,
      required: false,
      default() {
        return {
          gid: '',
          name: '',
          contentId: '',
          day: undefined,
          minTotal: undefined,
          discount: undefined,
          type: undefined
        }
      }
    },
    userIds: {
      type: String, // 多个用户组就用逗号间隔
      required: false,
      default() {
        return ''
      }
    },
    number: {
      type: Number, // 多个用户组就用逗号间隔
      required: false,
      default() {
        return 0
      }
    }
  },
  data() {
    return {
      coupongid: '',
      couponOptions: [],
      dialogFormVisible: false,
      loading: false
    }
  },
  watch: {
    dialogFormVisible(newValue) {
      this.couponOptions = []
      if (newValue) {
        if (this.coupon.gid) {
          this.coupongid = this.coupon.gid
          this.getCoupon({ gid: this.coupongid })
        } else {
          this.getCoupon({ })
        }
      }
    }
  },
  methods: {
    getCoupon(data) {
      data = data || {}
      this.dialogFormVisible = true
      getCoupon(data).then(res => {
        this.couponOptions = res.result.list
        this.loading = false
      })
    },
    remoteMethod(keyword) {
      this.loading = true
      this.getCoupon({ keyword })
    },
    // 发放优惠券
    provideCoupon() {
      grant({ userIds: this.userIds, couponId: this.coupongid }).then(res => {
        this.$message({
          message: '发放成功~',
          type: 'success'
        })
        this.dialogFormVisible = false
      })
    }
  }
}
</script>
